package com.supercwn.player.app.manager.util;

import android.content.Context;
import android.text.TextUtils;
import android.util.Log;

import com.supercwn.player.app.manager.bean.StorageBean;

import java.io.File;
import java.io.FileInputStream;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;

/**
 * 项目名称：SuperPlayer-master
 * 类描述：文件清理
 * 创建人：TianGenhu
 * 创建时间：2017/12/7 14:12
 * 修改人：TianGenhu
 * 修改时间：2017/12/7 14:12
 * 修改备注：
 */

public class CleanFileManager {
    private static final String TAG = "TGH";
    private Context mContext;
    private static volatile CleanFileManager cleanFileManager;

    private CleanFileManager(Context context) {
        mContext = context;
    }

    public static synchronized CleanFileManager getInstance(Context context) {
        if (cleanFileManager == null) {
            cleanFileManager = new CleanFileManager(context);
        }
        return cleanFileManager;
    }

    // 获取文件
    //Context.getExternalFilesDir() --> SDCard/Android/data/你的应用的包名/files/ 目录，一般放一些长时间保存的数据
    //Context.getExternalCacheDir() --> SDCard/Android/data/你的应用包名/cache/目录，一般存放临时缓存数据
    public static long getFolderSize(File file) throws Exception {
        long size = 0;
        try {
            File[] fileList = file.listFiles();
            for (int i = 0; i < fileList.length; i++) {
                // 如果下面还有文件
                if (fileList[i].isDirectory()) {
                    size = size + getFolderSize(fileList[i]);
                } else {
                    size = size + fileList[i].length();
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return size;
    }

    /**
     * 删除指定目录下文件及目录
     *
     * @param deleteThisPath
     * @return
     */
    public static void deleteFolderFile(String filePath, boolean deleteThisPath) {
        if (!TextUtils.isEmpty(filePath)) {
            try {
                File file = new File(filePath);
                if (file.isDirectory()) {// 如果下面还有文件
                    File files[] = file.listFiles();
                    for (int i = 0; i < files.length; i++) {
                        deleteFolderFile(files[i].getAbsolutePath(), true);
                    }
                }
                if (deleteThisPath) {
                    if (!file.isDirectory()) {// 如果是文件，删除
                        file.delete();
                        Log.i(TAG, "删除文件成功  1");
                    } else {// 目录
                        if (file.listFiles().length == 0) {// 目录下没有文件或者目录，删除
                            file.delete();
                            Log.i(TAG, "删除文件成功  2");
                        }
                    }
                }
            } catch (Exception e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
                Log.i(TAG, "删除文件异常  ：" + e);
            }
        }
    }

    /**
     * 格式化单位
     *
     * @param size
     * @return
     */
    public static String getFormatSize(double size) {
        double kiloByte = size / 1024;
        if (kiloByte < 1) {
            return size + "Byte";
        }

        double megaByte = kiloByte / 1024;
        if (megaByte < 1) {
            BigDecimal result1 = new BigDecimal(Double.toString(kiloByte));
            return result1.setScale(2, BigDecimal.ROUND_HALF_UP)
                    .toPlainString() + "KB";
        }

        double gigaByte = megaByte / 1024;
        if (gigaByte < 1) {
            BigDecimal result2 = new BigDecimal(Double.toString(megaByte));
            return result2.setScale(2, BigDecimal.ROUND_HALF_UP)
                    .toPlainString() + "MB";
        }

        double teraBytes = gigaByte / 1024;
        if (teraBytes < 1) {
            BigDecimal result3 = new BigDecimal(Double.toString(gigaByte));
            return result3.setScale(2, BigDecimal.ROUND_HALF_UP)
                    .toPlainString() + "GB";
        }
        BigDecimal result4 = new BigDecimal(teraBytes);
        return result4.setScale(2, BigDecimal.ROUND_HALF_UP).toPlainString()
                + "TB";
    }


    public static String getCacheSize(File file) throws Exception {
        return getFormatSize(getFolderSize(file));
    }


    /*************************************/

    //no recursion
    public static List<StorageBean> listLinkedFiles(String strPath) {
        List<StorageBean> listStorage = new ArrayList<>();
        LinkedList<File> list = new LinkedList<File>();
        File dir = new File(strPath);
        File[] file = dir.listFiles();
        for (int i = 0; i < file.length; i++) {
            if (file[i].isDirectory()) {
                list.add(file[i]);
            } else {
                try {
                    StorageBean mStorageBean = new StorageBean();
                    mStorageBean.setUrl(file[i].getAbsolutePath());
                    String absolutePath = file[i].getAbsolutePath();
                    File filePath = new File(absolutePath);
                    long fileSizes = getFileSizes(filePath);
                    mStorageBean.setSize(fileSizes);
                    listStorage.add(mStorageBean);
                    Log.i(TAG, " 7   存储URL  ：" + file[i].getAbsolutePath());
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }
        File tmp;
        while (!list.isEmpty()) {
            tmp = (File) list.removeFirst();//移除第一个，并且同时输出第一个
            if (tmp.isDirectory()) {
                file = tmp.listFiles();
                if (file == null)
                    continue;
                for (int i = 0; i < file.length; i++) {
                    if (file[i].isDirectory()) {
                        list.add(file[i]);
                    } else {
                        try {
                            String absolutePath = file[i].getAbsolutePath();
                            File filePath = new File(absolutePath);
                            long fileSizes = getFileSizes(filePath);
                            StorageBean mStorageBean = new StorageBean();
                            mStorageBean.setUrl(file[i].getAbsolutePath());
                            mStorageBean.setSize(fileSizes);//getFormatSize(fileSizes)
                            listStorage.add(mStorageBean);
                        } catch (Exception e) {
                            e.printStackTrace();
                        }

                    }
                }
            } else {
                Log.i(TAG, " 9   存储URL  ：" + tmp.getAbsolutePath());
            }
        }
        return listStorage;
    }


    //recursion
    public static ArrayList<File> listFiles(String strPath) {
        return refreshFileList(strPath);
    }

    public static ArrayList<File> refreshFileList(String strPath) {
        ArrayList<File> filelist = new ArrayList<File>();
        File dir = new File(strPath);
        File[] files = dir.listFiles();

        if (files == null)
            return null;
        for (int i = 0; i < files.length; i++) {
            if (files[i].isDirectory()) {
                refreshFileList(files[i].getAbsolutePath());
            } else {
                if (files[i].getName().toLowerCase().endsWith("zip"))
                    filelist.add(files[i]);
            }
        }
        return filelist;
    }


    public static long getFileSizes(File f) throws Exception {

        long s = 0;
        if (f.exists()) {
            FileInputStream fis = null;
            fis = new FileInputStream(f);
            s = fis.available();
            fis.close();
        } else {
            f.createNewFile();
            System.out.println("文件夹不存在");
        }

        return s;
    }


}
